#include "Console.h"

#ifndef _USE_OLD_IOSTREAMS
using namespace std;
#endif

void Console::redirectIOToConsole()
{
   // allocate a console for this app
   AllocConsole();

   // set the screen buffer to be big enough to let us scroll text
   GetConsoleScreenBufferInfo( GetStdHandle(STD_OUTPUT_HANDLE), &m_consoleBufferInfo );

   m_consoleBufferInfo.dwSize.Y = m_maxConsoleLines;

   SetConsoleScreenBufferSize( GetStdHandle(STD_OUTPUT_HANDLE), m_consoleBufferInfo.dwSize );

   // redirect unbuffered STDOUT to the console
   m_stdHandle = (long)GetStdHandle( STD_OUTPUT_HANDLE );
   m_consoleHandle = _open_osfhandle( m_stdHandle, _O_TEXT );
   m_pFile = _fdopen( m_consoleHandle, "w" );
   *stdout = *m_pFile;
   setvbuf( stdout, NULL, _IONBF, 0 );

   // redirect unbuffered STDIN to the console
   m_stdHandle = (long)GetStdHandle( STD_INPUT_HANDLE );
   m_consoleHandle = _open_osfhandle( m_stdHandle, _O_TEXT );
   m_pFile = _fdopen( m_consoleHandle, "r" );
   *stdin = *m_pFile;
   setvbuf( stdin, NULL, _IONBF, 0 );

   // redirect unbuffered STDERR to the console
   m_stdHandle = (long)GetStdHandle( STD_ERROR_HANDLE );
   m_consoleHandle = _open_osfhandle( m_stdHandle, _O_TEXT );
   m_pFile = _fdopen( m_consoleHandle, "w" );
   *stderr = *m_pFile;
   setvbuf( stderr, NULL, _IONBF, 0 );

   // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog point to console as well
   ios::sync_with_stdio();
}

void Console::create(WORD maxConsoleLines /* = 1000 */)
{
#ifdef _DEBUG

   this->redirectIOToConsole();
   std::cout << "Debug Messages:" << std::endl;

#endif//_DEBUG
}